package net.lainiao.manager.control;

import net.lainiao.base.model.ReptileFilter;
import net.lainiao.service.service.ReptileFilterService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2017/1/9.
 */
@Controller
@RequestMapping("/reptile/filter")
public class ReptileFilterControl {

    @Resource
    private ReptileFilterService reptileFilterService;

    private String baseDir = "/reptile/filter/";

    @RequestMapping(value = "/index/{tid}")
    public String index(ModelMap modelMap, @PathVariable int tid) {
        List<ReptileFilter> list = reptileFilterService.getListForTid(tid);
        modelMap.put("models", list);
        return baseDir + "index";
    }

    @RequestMapping(value = "/del/{tid}/{id}")
    public String del(ModelMap modelMap,@PathVariable int tid
            ,@PathVariable int id) {
        reptileFilterService.delete(id);
        return "redirect:/reptile/filter/index/" + tid;
    }


    @RequestMapping(value = "/add/{tid}", method = RequestMethod.GET)
    public String add(ModelMap modelMap, @PathVariable int tid) {
        modelMap.put("tid", tid);
        return baseDir + "add";
    }

    @RequestMapping(value = "/add/{tid}", method = RequestMethod.POST)
    public String add(ModelMap modelMap, @PathVariable int tid, @ModelAttribute ReptileFilter reptileFilter) {
        if (reptileFilterService.save(reptileFilter) > 0) {
            return "redirect:/reptile/filter/index/" + tid;
        }
        modelMap.put("net.lainiao.zhihu.model", reptileFilter);
        modelMap.put("mess", "保存失败");
        return add(modelMap, tid);
    }

    @RequestMapping(value = "/edit/{tid}/{id}", method = RequestMethod.GET)
    public String edit(ModelMap modelMap, @PathVariable int tid, @PathVariable int id) {
        ReptileFilter reptileFilter = reptileFilterService.getInfo(id);
        modelMap.put("net.lainiao.zhihu.model", reptileFilter);
        return baseDir + "edit";
    }

    @RequestMapping(value = "/edit/{tid}", method = RequestMethod.POST)
    public String edit(ModelMap modelMap, @PathVariable int tid, @ModelAttribute ReptileFilter model) {
        if (reptileFilterService.save(model) > 0) {
            return "redirect:/reptile/filter/index/" + tid;
        }
        modelMap.put("mess", "保存失败");
        return edit(modelMap, tid, model.getId());
    }
}
